package com.tcpudp.controller;

import com.tcpudp.model.User;
import com.tcpudp.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private final UserService userService;
    
    public AuthController(UserService userService) {
        this.userService = userService;
    }
    
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> credentials, HttpSession session) {
        String username = credentials.get("username");
        String password = credentials.get("password");
        
        if (userService.validateUser(username, password)) {
            User user = userService.findByUsername(username);
            session.setAttribute("user", user);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "username", username,
                "role", user.getRole()
            ));
        } else {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "用户名或密码错误"
            ));
        }
    }
    
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession session) {
        session.invalidate();
        return ResponseEntity.ok(Map.of("success", true));
    }
    
    @GetMapping("/check")
    public ResponseEntity<?> checkLoginStatus(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return ResponseEntity.ok(Map.of(
                "loggedIn", true,
                "username", user.getUsername(),
                "role", user.getRole()
            ));
        } else {
            return ResponseEntity.status(401).body(Map.of(
                "loggedIn", false,
                "message", "未登录"
            ));
        }
    }
}